package com.imooc.rabbitMQ;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * 生产者
 *
 * @author: 顾志杰
 */
public class Producer {

    public static void main(String[] args)throws Exception {
        //1 创建一个ConnectionFactory, 并进行配置
        ConnectionFactory connectionFactory = new ConnectionFactory();
        // host就是你的RabbitMQ所在的虚拟机地址，我这里是192.168.35.133；默认端口是5672 ;
         connectionFactory.setHost("192.168.35.133");
         connectionFactory.setPort(5672);
         connectionFactory.setVirtualHost("/");
        connectionFactory.setUsername("menghun");
        connectionFactory.setPassword("123456");

        //2 通过连接工厂创建连接
        Connection connection = connectionFactory.newConnection();


        //3 通过connection创建一个Channel
        Channel channel = connection.createChannel();

        //4 声明（创建）一个队列
        String queueName = "queue-1";
        channel.queueDeclare(queueName, true, false, false, null);

        Map<String,Object> headers = new HashMap<String,Object>();

        AMQP.BasicProperties props = new AMQP.BasicProperties().builder()
                .deliveryMode(2)
                .contentEncoding("UTF-8")
                .headers(headers).build();
        //5 通过Channel发送消息，这里我发送了5条消息哦
        for(int i=0; i < 5; i++){
            String msg = "Hello RabbitMQ!";
            //1 exchange   2 routingKey
            channel.basicPublish("", queueName, props, msg.getBytes());
        }

        //6 记得要关闭相关的连接
        channel.close();
        connection.close();
    }
}
